/*
 ============================================================================
 Name        : phase_para.c
 Author      : chenf
 Version     :
 Copyright   : loongsec
 Description : CRUD phase_parm table, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"
#include "stdx.h"

void put_json(char **azResult, int nrow, int ncolumn);

void put_error(char *err_msg){
    printf("Content-type:text/html;charset=UTF-8\n\n");
	printf("%s.\n", err_msg);
}

int main(void) {
    sqlite3  *db  = NULL;
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    char     sql[500];
    char     *input;
    char     *req_method;
    int      rc;

    if(isvalid_cookie() != 0){
        return 0;
    }

    rc = sqlite3_open(PATH_DATABASE,&db);
    if (rc) {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        put_error((char*)sqlite3_errmsg(db));
        return 0;

    } else {

    	req_method = getenv("REQUEST_METHOD");

		FILE* fp = (FILE*) stdin;
	    input = getcgidata(fp, req_method);

	    PARAM id = getParam(input, "id");

        if( strcmp(id.value, "") != 0 && strcmp(id.value, "null") != 0 ){
			 sprintf(sql, "select * from [tb_phase_parm] where phase_index = %s ", id.value);
		} else {
			 sprintf(sql, "select * from [tb_phase_parm]");
		}

        rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr,"SQL error:%s\n", zErrMsg);
            put_error(zErrMsg);
            sqlite3_close(db);
            return 0;
        } 
        
        printf("Content-type:text/json;charset=UTF-8\n\n");
        
        printf("{\"phase\":");
        
        if (*azResult != NULL) {
			put_json(azResult, nrow, ncolumn); 
        }
         printf(", \"phase_channel\":");
        /* get phase channel */
        if( strcmp(id.value, "") != 0 && strcmp(id.value, "null") != 0 ){
             sprintf(sql, "select channel_index from [tb_channel_parm] where channel_ctrl_signal_source = %s ", id.value);
        } 
        
        rc = sqlite3_get_table(db, sql, &azResult, &nrow, &ncolumn, &zErrMsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr,"SQL error:%s\n", zErrMsg);
            put_error(zErrMsg);
            sqlite3_close(db);
            return 0;
        } 
        if (*azResult != NULL) {
			put_json(azResult, nrow, ncolumn); 
        }
         printf("}\n");
    }

    sqlite3_close(db);
    return 0;

}

void put_json(char **azResult, int nrow, int ncolumn){
	int i=0, j=0, n=0;	
	printf("{ \"rows\": \"%d\", \"data\": [", nrow);
    for(i=1; i<=nrow; i++) {
        printf("{");
		char *phaseIndex = {0};
        for(j=0; j<ncolumn; j++) {
			if(j==0){
				phaseIndex = azResult[ (i*ncolumn) + j ];
			}
			printf("\"%s\": \"", azResult[j]);

			if(j==9 || j==10){
				char t[100];
				printf("%s", _itoa(
							atoi(  azResult[ (i*ncolumn) + j ] ),
							t, 2) );
			} else if(strcmp(azResult[j], "green_flash_time") == 0){			   
			    printf("%.1f",  atof(azResult[ (i*ncolumn) + j ]) / 10 );
			} else {
				printf("%s", azResult[ (i*ncolumn) + j ]);
			}
            //printf(azResult[ (i*ncolumn) + j ]);

            if(j == ncolumn-1)
				printf("\"");
			else
				printf("\",");
            n++;
        }
        if(i == nrow)
			printf("}\n\n");
		else
			printf("},\n\n");
    }
    printf("]}");
}
